<template>
  <div class="main-content">
    <div class="view-title">
      <!--      <h2>版本管理</h2>-->
    </div>
    <div class="table-bar">
      <tool-bar
        :cond.sync="filterBy"
        @callback="handleCallback"
      />
    </div>
    <div class="table-content">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        border
        class="table"
        max-height="700"
        header-cell-class-name="table-header"
        tooltip-effect="light"
        :default-sort="defaultSortConf"
        @sort-change="changeSort"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" width="50" align="center" label="序号" />
        <template v-for="item in tableColumn">
          <el-table-column
            :key="item.index"
            :prop="item.index"
            :width="item.width"
            :label="item.label"
            :sortable="item.sortable"
            :formatter="item.formatter"
            :show-overflow-tooltip="item.tip"
          />
        </template>
      </el-table>
    </div>
    <div class="table-footer">
      <el-pagination
        :current-page="pageInfo.pageNum"
        :page-sizes="pageInfo.sizeItems"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.totalSize"
        :page-count="pageInfo.totalPages"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<script>
import fota from '../../api/fota'
import apiConst from '../../common/js/apiConst'
import { formatTimeToStr } from '../../utils/index'
import ToolBar from './toolBar'

export default {
  components: { ToolBar },
  data() {
    return {
      loading: false,
      tableColumn: [],
      tableData: [],
      servers: [],
      pageInfo: {},
      sortConf: {},
      defaultSortConf: { prop: 'createTime', order: 'descending' },
      filterBy: { createRange: [], updateRange: [] }
    }
  },
  created() {
    this.initTableBaseInfo()
  },
  mounted() {
    this.loadData()
  },
  methods: {
    handleCallback(cmd) {
      switch (cmd) {
        case 'refresh':
          this.refresh()
          break
        case 'search':
          this.handleSearch()
          break
        case 'export_all':
          this.handleExport(apiConst.EXPORT_TYPE.ALL)
          break
        case 'export_ytl':
          this.filterBy.operator = apiConst.LOG_TYPE.DOWNLOAD
          this.handleExport(apiConst.EXPORT_TYPE.YTL)
          break
        default:
          console.log(`unknown cmd:${cmd}`)
      }
    },
    handleExport(type) {
      const self = this
      self.loading = true
      fota.exportLog({ type: type, filter: this.filterBy }).then(resp => {
        const fileNameMsg = resp.headers['content-disposition'].split(';')[1]
        const fileName = fileNameMsg.substring('filename="'.length, fileNameMsg.length - 1)
        const content = resp.data
        const blob = new Blob([content], {
          type: 'application/vnd.ms-excel'
        }) // 构造一个blob对象来处理数据
        // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
        // IE10以上支持blob但是依然不支持download
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a') // 创建a标签
          link.download = fileName // a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click() // 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link) // 释放标签
        } else { // 其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
        self.loading = false
      }, () => {
        fota.notifyError(`FOTA日志导出失败！`)
        self.loading = false
      })
    },
    handleSearch() {
      this.loadData()
    },
    refresh() {
      this.filterBy = { createRange: [], updateRange: [] }
      this.loadData()
    },
    initTableBaseInfo() {
      this.tableColumn = [
        { index: 'imei', label: 'IMEI', tip: true, sortable: 'custom' },
        { index: 'product', label: '产品', tip: true, sortable: 'custom' },
        { index: 'fromV', label: '当前版本', tip: true, sortable: 'custom' },
        { index: 'toV', label: '目标版本', tip: true, sortable: 'custom' },
        { index: 'reqServer', label: '用户IP', tip: true, sortable: 'custom' },
        { index: 'respServer', label: '响应服务器', width: 116, tip: true, formatter: this.serverFormatter, sortable: 'custom' },
        { index: 'count', label: '计数', width: 80, tip: true, sortable: 'custom' },
        { index: 'createTime', label: '创建时间', tip: true, formatter: this.timeFormatter, sortable: 'custom' },
        { index: 'updateTime', label: '更新时间', tip: true, formatter: (row) => formatTimeToStr(row.updateTime), sortable: 'custom' },
        { index: 'operator', label: '操作类型', width: 80, formatter: this.operatorFormatter },
        { index: 'autoDownload', label: '下载类型', width: 80, formatter: this.autoDownloadFormatter }
      ]
      this.pageInfo = {
        pageNum: 1,
        pageSize: 10,
        totalPages: 1,
        totalSize: 1,
        sizeItems: [10, 20, 50, 100, 200, 500, 1000]
      }
      this.sortConf = this.defaultSortConf
    },
    handleSizeChange: function(newSize) {
      this.pageInfo.pageSize = newSize
      this.loading = true
      this.initTableData()
    },
    handleCurrentChange: function(pageNum) {
      this.pageInfo.pageNum = pageNum
      this.loading = true
      this.initTableData()
    },
    initTableData: function() {
      const self = this
      const param = { pageNum: this.pageInfo.pageNum, pageSize: this.pageInfo.pageSize, orderBy: this.getOrderByCond(), filterBy: this.filterBy }
      fota.queryLogList(param).then(res => {
        self.tableData = res.data.data
        self.pageInfo.totalPages = res.data.totalPages
        self.pageInfo.totalSize = res.data.totalSize
        self.loading = false
      }, () => {
        fota.notifyError(`FOTA日志查询失败！`)
        self.loading = false
      })
    },
    initFotaServers: function() {
      const self = this
      fota.queryFotaServers().then(res => {
        self.servers = res.data.servers
        self.loading = false
      }, () => {
        fota.notifyError(`服务器信息查询失败！`)
        self.loading = false
      })
    },
    changeSort: function({ prop, order }) {
      if (order === null) {
        this.sortConf = this.defaultSortConf
      } else {
        this.sortConf = { prop: prop, order: order }
      }
      this.loadData()
    },
    getOrderByCond() {
      const columnMapping = { fromV: 'from_v', toV: 'to_v', reqServer: 'req_server', respServer: 'resp_server', createTime: 'create_time', updateTime: 'update_time' }
      const orderMapper = { descending: 'desc', ascending: 'asc' }
      return `${(columnMapping[this.sortConf.prop] || this.sortConf.prop)} ${orderMapper[this.sortConf.order]}`
    },
    loadData() {
      this.loading = true
      this.initTableData()
      this.initFotaServers()
    },
    timeFormatter: function(row) {
      return formatTimeToStr(row.createTime)
    },
    operatorFormatter: function(row) {
      switch (row.operator) {
        case apiConst.LOG_TYPE.QUERY:
          return '查询'
        case apiConst.LOG_TYPE.DOWNLOAD:
          return '下载'
        default:
          return '查询'
      }
    },
    autoDownloadFormatter: function(row) {
      return row.autoDownload === 1 ? '手动' : '自动'
    },
    serverFormatter: function(row) {
      if (row.operator === apiConst.LOG_TYPE.QUERY) {
        return '管理服务器'
      }
      const ip = row.respServer
      const item = this.servers.filter(item => {
        const address = item.domain
        return address && address.match(/([^:]*):?.*/)[1] === ip
      })
      return item === null || item.length === 0 ? `${ip} [undefined]` : item[0].name
    }
  }
}
</script>

<style scoped>
  .main-content {
    padding: 16px;
  }

  .table-bar {
    margin: 0 8px 8px 0;
  }

  .table-footer {
    float: right;
    margin-top: 8px;
  }
</style>
